#include<iostream>
using namespace std;
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
  class Solution {
  public:
      ListNode* addTwoNumbers(ListNode* l, ListNode* r)
      {
          ListNode* ans = new ListNode(0), * now = ans, * pre = nullptr;
          while (l || r)
          {
              if (l)
              {
                  ans->val += l->val;
                  l = l->next;
              }
              if (r)
              {
                  ans->val += r->val;
                  r = r->next;
              }
              pre = ans;
              ans->next = new ListNode(ans->val / 10);
              ans->val %= 10;
              ans = ans->next;
          }
          if (ans->val >= 10)
          {
              ans->next = new ListNode(ans->val / 10);
              ans->val %= 10;
              ans = ans->next;
              return now;
          }
          if (ans->val == 0)
          {
              delete ans;
              pre->next = nullptr;
          }
          return now;
      }
  };